<template>
  <div class="login-box">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="90px"
      class="demo-ruleForm"
    >
      <h2>后台管理系统</h2>
      <el-form-item label="账号：" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" cleared />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >登录</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'
import { LoginData } from '../type/login'
import { login } from '../request/api'

export default defineComponent({
    setup () {
        const data = reactive(new LoginData())

        const rules = {
          username: [
            { required: true, message: '请输入账号', trigger: 'blur' },
            { min: 3, max: 10, message: '账号的长度在3-10个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 10, message: '密码的长度在3-10个字符', trigger: 'blur' }
          ]
        }

        // 登录
        const ruleFormRef = ref<FormInstance>()
        const router = useRouter()
        const submitForm = (formEl: FormInstance | undefined) => {
          if (!formEl) return
          formEl.validate(valid => {
            if (valid) {
              login(data.ruleForm).then(res => {
                localStorage.setItem('token', res.data.token)
                router.replace({ path: '/' })
              })
            } else {
              console.log('error submit')
              return false
            }
          })
        }

        // 重置
        const resetForm = (formEl: FormInstance | undefined) => {
          if (!formEl) return
          formEl.resetFields()
        }

        return {
          ...toRefs(data),
          rules,
          ruleFormRef,
          resetForm,
          submitForm
        }
    }
})
</script>

<style lang="less" scoped>
.login-box{
  width: 100%;
  height: 100%;
  background: url('../assets/7acd0a3451c833ab2c6eec0fb48f35d5.jpg');
  overflow: hidden;
  text-align: center;
  .demo-ruleForm{
    width: 500px;
    margin: 200px auto;
    background-color: #fff;
    padding: 40px;
    border-radius: 10px;
    h2{
      margin-bottom: 10px;
    }
  }
}
</style>